package com.cby.web.controller;

import com.cby.web.bean.Data;
import com.cby.web.bean.Info;
import com.cby.web.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/api")
public class ApiController {

    @RequestMapping("/null")
    public void testNullPointerException() {
        User user = null;
        //这里就会发生空指针异常，然后就会返回定义在SpringMVC配置文件中的null视图
        System.out.println(user.toString());
    }

    @RequestMapping("/number")
    public String testNumberFormatException(String number) {
        System.out.println("number = "+number);
        //这里就会发生NumberFormatException，然后就会返回定义在SpringMVC配置文件中的number视图
        Integer i = Integer.parseInt(number);
        return "/number";
    }

    @RequestMapping("/default")
    public void testDefaultException(){
        throw new RuntimeException("default exception！");
    }

    @RequestMapping("/show")
    public String say(HttpServletRequest request){
        System.out.println("show....");
        request.setAttribute("name","Jason"); // 指定Model的值
        //return "/index.jsp";
        return "/demo";
    }

    @RequestMapping("/get")
    @ResponseBody
    public Data get(Info info) {
        System.out.println("get...."+info.toString());
        return dealWith(info);
    }

    private Data dealWith(Info info) {
        Data data = new Data();
        String nickName = info.getNickname();
        String gender = info.getGender();
        int age = info.getAge();
        if (StringUtils.isEmpty(nickName)){
            return data.setCode(-1).setResult("nick name is null");
        } else if (StringUtils.isEmpty(gender)){
            return data.setCode(-2).setResult("gender is null");
        } else if (age == 0){
            return data.setCode(-3).setResult("age is null");
        }
        return data.setCode(200).setResult(info.toString());
    }
}
